package com.demo.serializer;

import java.lang.reflect.Type;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;


/**
 * gson序列化
 *
 */
public class GsonSerializer implements ISerializer {
	//初始化logger
	private static final Logger logger = LoggerFactory.getLogger(GsonSerializer.class);
	//初始化GsonSerializer实例
	private static GsonSerializer instance = new GsonSerializer();
	
	/**
	 * 无参构造
	 */
	private GsonSerializer() {
		
	}
	
	/**
	 * 获取实例
	 * @return
	 */
	public static synchronized GsonSerializer getInstance() {
		if (null == instance) {
			instance = new GsonSerializer();
		}
			
		return instance;
	}
	/**
     * Object转为byteArray
     * @param object
     * @return
     */
	@Override
	public byte[] toByteArray(Object object) {
		try {
			return new Gson().toJson(object).getBytes("UTF-8");
		} catch (Exception e) {
			logger.error("GsonSerializer toByteArray error: " + e);
			throw new RuntimeException("GsonSerializer toByteArray error: " + e);
		}
	}
	/**
     * byte[] 转为Object
     * @param bytes
     * @param clazz
     * @return
     */
	@Override
	public <T> T toObject(byte[] bytes, Class<T> clazz) {
		try {
			return new Gson().fromJson(new String(bytes, "UTF-8"), clazz);
		} catch (Exception e) {
			logger.error("GsonSerializer toObject error: " + e);
			throw new RuntimeException("GsonSerializer toObject error: " + e);
		}
	}
	/**
     * byte[] 转为Object
     * @param bytes
     * @param type
     * @return
     */
	@Override
	public <T> T toObject(byte[] bytes, Type type) {
		try {
			return new Gson().fromJson(new String(bytes, "UTF-8"), type);
		} catch (Exception e) {
			logger.error("GsonSerializer toObject error: " + e);
			throw new RuntimeException("GsonSerializer toObject error: " + e);
		}
	}
	/**
     * 获取type
     * @return
     */
	@Override
	public SerializerType getType() {
		return SerializerType.GSON;
	}
}
